package com.zclever.kstarwar.websocket;

import com.google.gson.Gson;
import com.zclever.kstarwar.service.MessageService;
import com.zclever.kstarwar.vo.Message;
import com.zclever.kstarwar.vo.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 对战webSocket服务端
 * @author zclever
 * @email 304078606@qq.com
 * @date 2019/8/7
 */
@ServerEndpoint("/game/{uid}/{uname}")
@Component
public class WebSocketServer {

    private static final Logger logger = LogManager.getLogger(WebSocketServer.class);

    private Session session;
    private User user;

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    private static Gson gson = new Gson();

    private static MessageService messageService;

    @OnOpen
    public void onOpen(Session session,@PathParam("uid") int uid,@PathParam("uname") String uname) throws Exception{
        logger.info("用户连接:{},{}",uid,uname);

        this.session = session;
        this.user = new User();
        this.user.setUid(uid);
        this.user.setUname(uname);

        webSocketSet.add(this);
    }

    @OnMessage
    public void onMessage(Session session,String json) throws Exception{
        logger.info("用户发送消息:{}",json);

        Message message = gson.fromJson(json,Message.class);

        messageService.dealMessage(user,message);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Message message) throws Exception {
        logger.info("推送消息:{}",message);

        String json = gson.toJson(message);
        this.session.getBasicRemote().sendText(json);
    }

    @OnClose
    public void onClose() {
        logger.error("关闭连接");
        webSocketSet.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error) {
        logger.error("发生错误");
        error.printStackTrace();
    }

    public User getUser() {
        return user;
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }

    @Resource
    public void setMessageService(MessageService messageService){
        WebSocketServer.messageService = messageService;
    }
}




